package com.example.service;

import org.springframework.scheduling.annotation.Scheduled;
import org.web3j.protocol.Web3j;
import org.web3j.protocol.core.methods.response.EthGasPrice;
import java.math.BigInteger;

import com.example.entity.GasPrice;
import com.example.mapper.GasPriceMapper;
import org.springframework.stereotype.Service;
import jakarta.annotation.Resource;

@Service
public class GasPriceService {

    @jakarta.annotation.Resource
    private Web3j web3j;

    @Resource
    private GasPriceMapper gasPriceMapper;

    /**
     * 每5分钟自动同步一次Gas价格
     * 需在配置类加 @EnableScheduling
     */
    @Scheduled(cron = "0 0/5 * * * ?")
    public void scheduledSyncGasPrice() {
        try {
            EthGasPrice ethGasPrice = web3j.ethGasPrice().send();
            BigInteger gasPriceWei = ethGasPrice.getGasPrice();
            GasPrice gasPrice = new GasPrice();
            gasPrice.setBaseGasPrice(gasPriceWei);
            gasPrice.setUpdateTime(new java.util.Date());
            syncGasPrice(gasPrice);
            System.out.println("[GasPriceService] 定时同步Gas价格: " + gasPriceWei);
        } catch (Exception e) {
            System.err.println("[GasPriceService] 获取Gas价格失败: " + e.getMessage());
        }
    }

    /**
     * 同步最新Gas价格
     */
    public void syncGasPrice(GasPrice gasPrice) {
        if (gasPrice == null || gasPrice.getBaseGasPrice() == null) return;
        
        gasPrice.setId(1L); // 固定唯一ID
        GasPrice exist = gasPriceMapper.selectById(1L);
        if (exist == null) {
            gasPriceMapper.insert(gasPrice);
        } else {
            gasPriceMapper.updateById(gasPrice);
        }
    }

}
